<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="noticeRuleId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="addTemplate">新增</el-button>
        <el-button type="primary" plain @click="EditGroup(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedList)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      表格操作
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="EditGroup([scope.row])">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { User, RoleManager, dataDictionary } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/dataDictionary/groupManagement/components/groupDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";
import { findNoticeRulePager, delNoticeRules } from "@/api/modules/systemTools";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import { dataDictionaryGroupFind, deleteGroup, exportDataDictionaryGroup } from "@/api/modules/dataDictionary";
const route = useRoute();
const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行

const dataCallback = (data: any) => {
  if (data.data != null) {
    data.data.forEach((child: resList) => {
      let str = "";
      if (child.mailNotice.toString() == "true") {
        if (str == "") {
          str += "邮箱通知";
        } else {
          str += ";邮箱通知";
        }
      }
      if (child.smsNotice.toString() == "true") {
        if (str == "") {
          str += "短信通知";
        } else {
          str += ";短信通知";
        }
      }
      if (child.imNotice.toString() == "true") {
        if (str == "") {
          str += "im消息通知";
        } else {
          str += ";im消息通知";
        }
      }
      if (child.pushNotice.toString() == "true") {
        if (str == "") {
          str += "手机消息推送";
        } else {
          str += ";手机消息推送";
        }
      }
      child["noticeTypeShow"] = str;
      let noticeRuleTypeShow = "";
      if (child.noticeRuleType.includes("requester")) {
        noticeRuleTypeShow += "请求人或报告人;";
      }
      if (child.noticeRuleType.includes("technician")) {
        noticeRuleTypeShow += "技术员;";
      }
      if (child.noticeRuleType.includes("technicalGroup")) {
        noticeRuleTypeShow += "技术组;";
      }
      if (child.noticeRuleType.includes("owner")) {
        noticeRuleTypeShow += "负责人;";
      }
      if (child.noticeRuleType.includes("taskGroupAndTechnician")) {
        noticeRuleTypeShow += "任务指派对象(组或技术员);";
      }
      if (child.noticeRuleType.includes("taskTechnicalGroupLeader")) {
        noticeRuleTypeShow += "指派组组长;";
      }
      if (child.noticeRuleType.includes("ciOwner")) {
        noticeRuleTypeShow += "负责人;";
      }
      if (child.noticeRuleType.includes("ciUse")) {
        noticeRuleTypeShow += "使用人;";
      }
      child["noticeRuleTypeShow"] = noticeRuleTypeShow;
    });
  }
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const settingAuthRoleIds = ref("");
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  setResourceByRoleIds(data + "-" + settingAuthRoleIds.value).then(res => {
    if (res.toString() == "true") {
      ElMessage.success("权限设置成功");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    } else {
      ElMessage.error("权限设置失败");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    }
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "noticeRuleId";
  newParams.sord = "desc";
  if (newParams.noticeType != null) {
    if (newParams.noticeType.includes("mailNotice")) {
      newParams.mailNotice = true;
    }
    if (newParams.noticeType.includes("smsNotice")) {
      newParams.smsNotice = true;
    }
    if (newParams.noticeType.includes("imNotice")) {
      newParams.imNotice = true;
    }
    if (newParams.noticeType.includes("pushNotice")) {
      newParams.pushNotice = true;
    }
  }
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findNoticeRulePager(newParams, "noticeRuleDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};
export interface resList {
  companyName: string;
  companyNo: string;
  dataFlag: string;
  emailAddress: string;

  emailTemp: string;
  emailTitleTemp: string;
  imNotice: boolean;
  imTemp: string;
  lastUpdater: string;
  mailNotice: boolean;
  module: string;
  noticeRuleId: number;
  noticeRuleName: string;
  noticeRuleNo: string;
  noticeRuleType: string;
  noticeWay: string;
  pushNotice: boolean;
  pushTemp: string;
  smsNotice: boolean;
  smsTemp: string;
  technician: string;
  technicianOrEmail: string;
  url: string;
  useStatus: boolean;
  noticeType: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "noticeRuleId", label: "Id", sortable: true, width: 80 },
  { prop: "noticeRuleName", label: "通知模板名称", search: { el: "input" }, sortable: true },
  {
    prop: "module",
    label: "模块",
    sortable: true,
    width: 122,
    enum: [
      {
        genderLabel: "请求管理",
        genderValue: "request"
      },
      {
        genderLabel: "问题管理",
        genderValue: "problem"
      },
      {
        genderLabel: "变更管理",
        genderValue: "change"
      },
      {
        genderLabel: "发布管理",
        genderValue: "release"
      },
      {
        genderLabel: "资产管理",
        genderValue: "cim"
      },
      {
        genderLabel: "任务管理",
        genderValue: "task"
      },
      {
        genderLabel: "其它",
        genderValue: "other"
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => (
      <>
        {scope.row.module === "request"
          ? "请求"
          : scope.row.module === "problem"
            ? "问题"
            : scope.row.module === "change"
              ? "变更"
              : scope.row.module === "release"
                ? "发布"
                : scope.row.module === "cim"
                  ? "配置项"
                  : scope.row.module === "task"
                    ? "任务"
                    : scope.row.module === "other"
                      ? "其它"
                      : "未定义类型"}
      </>
    )
  },
  { prop: "noticeRuleTypeShow", label: "通知对象", sortable: true },
  { prop: "noticeTypeShow", label: "通知方式", sortable: true },
  {
    prop: "noticeType",
    label: "通知方式",
    sortable: true,
    isShow: false,
    enum: [
      {
        genderLabel: "邮箱通知",
        genderValue: "mailNotice"
      },
      {
        genderLabel: "短信通知",
        genderValue: "smsNotice"
      },
      {
        genderLabel: "im消息通知",
        genderValue: "imNotice"
      },
      {
        genderLabel: "手机消息推送",
        genderValue: "pushNotice"
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true, multiple: true, placeholder: "可多选" } },
    render: scope => (
      <>
        {scope.row.mailNotice === true
          ? "邮箱通知"
          : scope.row.smsNotice === true
            ? "短信通知"
            : scope.row.imNotice === true
              ? "im消息通知"
              : scope.row.pushNotice === true
                ? "手机消息推送"
                : ""}
      </>
    )
  },
  {
    prop: "useStatus",
    label: "状态",
    sortable: true,
    width: 122,
    enum: [
      {
        genderLabel: "启用",
        genderValue: true
      },
      {
        genderLabel: "禁用",
        genderValue: false
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => <>{scope.row.useStatus === true ? "启用" : "禁用"}</>
  },
  { prop: "operation", label: "操作项", fixed: "right", width: 160 }
]);
const addTemplate = () => {
  router.push(`/system/tools/addNotificationTemplate?pageNo=${Math.random().toFixed(3)}`);
};
// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除
const deleteAccount = async (params: resList) => {
  batchDelete([params]);
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].noticeRuleId;
    } else {
      idsStr = idsStr + "&ids=" + id[i].noticeRuleId;
    }
    NameStr = NameStr + id[i].noticeRuleName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      delNoticeRules(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const EditGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一条数据");
    return;
  } else if (id.length == 1) {
    router.push(`/system/tools/editNotificationTemplate?id=` + id[0].noticeRuleId);
  } else {
    ElMessage.error("只能编辑一条数据");
    return;
  }
};
</script>
